import json
import requests
from flask import Blueprint, request, jsonify
from config import APPID, APPSecret
from extension import db
from models.miniprogram_model import User
from models.models import UserModel
import time
import secrets
import string



bp=Blueprint('mysqlcrud',__name__,url_prefix='/mysqlcruduser')

def request_openid_from_wx(code):
    req_params = {
        'appid': APPID,
        'secret': APPSecret,
        'js_code': code,
        'grant_type': 'authorization_code'
    }
    wx_login_api = 'https://api.weixin.qq.com/sns/jscode2session'
    try:
        response_data = requests.get(wx_login_api, params=req_params)
        response_data.raise_for_status()  # 如果请求不成功，会引发 HTTPError
        return response_data.json()
    except requests.RequestException as e:
        print(e)
        # logger.error(f"Failed to request openid from WeChat: {e}")
        return None




@bp.route('/get_openid', methods=['POST'])
def get_openid():
    try:
        # wxlogincode = json.loads(logincode)调试形参可传，网络请求只能通过协议传参
        wxlogincode = json.loads(request.get_data().decode('utf-8'))
        code = wxlogincode.get('code')
        if code is None:
            # logger.error("No 'code' in the request data")
            return jsonify({"error": "Invalid request data, 'code' is missing"}), 400
    except json.JSONDecodeError as e:
        # logger.error(f"Failed to decode JSON data: {e}")

        return jsonify({"error": "Invalid JSON data"}), 400
    data = request_openid_from_wx(code)
    if data is None:
        return jsonify({"error": "openid请求失败！"}), 500
    openid = data.get('openid')
    session_key = data.get('session_key')
    if openid and session_key:
        return openid
    else:
        return None


@bp.route('/createuser', methods=['POST'])
def getorcreate_user():
    try:
        data = request.json
        print(data)
        # 必须要有openid作为用户唯一标识
        if 'openid' not in data:
            return jsonify({'error': 'Missing required field: openid'}), 400
        # 查询用户是否已存在
        user = User.query.filter_by(openid=data['openid']).first()
        if user:
            # 用户存在，返回用户信息
            return jsonify({
                'message': 'User found',
                'user_id': user.id,
                'username': user.username,
                'nickname': user.nickname,
                'avatar': user.avatar,
                'create_time': user.create_time.isoformat(),
                'is_new_user': False
            }), 200
        else:
            # 用户不存在，检查创建所需字段
            create_required = ['nickname', 'avatar']  # 创建用户必须的字段
            for field in create_required:
                if field not in data:
                    return jsonify({'error': f'Missing required field for user creation: {field}'}), 400

            # 创建新用户
            new_user = User(
                openid=data['openid'],
                avatar=data['avatar'],
                nickname=data.get('nickname', data['nickname'])
            )
            db.session.add(new_user)
            db.session.commit()

            return jsonify({
                'message': 'User created successfully',
                'user_id': new_user.id,
                'username': new_user.username,
                'nickname': new_user.nickname,
                'avatar': new_user.avatar,
                'create_time': new_user.create_time.isoformat(),
                'is_new_user': True
            }), 201

    except Exception as e:
        db.session.rollback()
        print(e)
        # logger.error(f'Error in getorcreate_user: {str(e)}')
        return jsonify({'error': 'Internal server error'}), 500
'''
1.添加唯一性检查 (特别是 openid)
2.增加输入验证 (长度、格式等)
3.考虑使用Flask-Marshmallow等库进行数据验证和序列化
4.在生产环境中，应该记录错误而不是直接返回给客户端
5.可以添加速率限制防止滥用
'''

# 应该是上面做好判断如果库有就别执行后面了
@bp.route('/storeuserinfo', methods=['POST'])
def storeuserinfo():
    # 拿到用户名头像openid
    data = json.loads(request.get_data().decode('utf-8'))
    # print(data)
    user_info =getorcreate_user(data)
    # print(user_info)
    return jsonify(user_info)